import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:craze/common/index.dart';
import 'package:craze/models/index.dart';
import 'package:craze/services/ai_service.dart';
import 'package:craze/services/service_locator.dart';
import 'package:craze/stores/auth_store.dart';
import 'package:craze/stores/scan_result_store.dart';

class AIResultView extends StatefulWidget {
  final File? imageFile;
  final String question;

  const AIResultView({
    Key? key,
    required this.imageFile,
    required this.question,
  }) : super(key: key);

  @override
  State<AIResultView> createState() => _AIResultViewState();
}

class _AIResultViewState extends State<AIResultView> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final AIService _aiService = getIt<AIService>();
  final ScanResultStore _scanResultStore = getIt<ScanResultStore>();
  final List<Map<String, dynamic>> _messages = [];
  ScanResultModel? _scanResult;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initializeChat();
  }

  Future<void> _initializeChat() async {
    // 添加用户的图片消息
    setState(() {
      _messages.add({
        'isUser': true,
        'content': 'image',
        'imageFile': widget.imageFile,
        'timestamp': DateTime.now(),
      });

      // 添加用户的文字问题
      _messages.add({
        'isUser': true,
        'content': widget.question,
        'timestamp': DateTime.now(),
      });

      _isLoading = true;
    });

    // 发送图片和问题到AI
    final authStore = getIt.get<AuthStore>();
    if (authStore.currentUser != null && widget.imageFile != null) {
      final result = await _aiService.sendImageAndQuestion(
        userId: authStore.currentUser!.id,
        imageFile: widget.imageFile!,
        question: widget.question,
      );

      if (result['success']) {
        setState(() {
          _scanResult = result['scanResult'] as ScanResultModel;

          // 添加AI的回复
          _messages.add({
            'isUser': false,
            'content': result['response'],
            'timestamp': DateTime.now(),
          });

          _isLoading = false;
        });

        // 成功获取扫描结果后，更新ScanResultStore
        await _scanResultStore.loadScanResults();

        // 滚动到底部
        WidgetsBinding.instance.addPostFrameCallback((_) {
          _scrollToBottom();
        });
      } else {
        setState(() {
          _isLoading = false;
          // 添加错误消息
          _messages.add({
            'isUser': false,
            'content': 'Sorry, I cannot process this image. ${result['error']}',
            'timestamp': DateTime.now(),
          });
        });
      }
    } else {
      setState(() {
        _isLoading = false;
        // 添加错误消息
        _messages.add({
          'isUser': false,
          'content': 'Please login or provide a valid image.',
          'timestamp': DateTime.now(),
        });
      });
    }
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  // 发送新消息
  Future<void> _sendMessage() async {
    if (_messageController.text.trim().isEmpty) return;

    final userMessage = _messageController.text.trim();
    _messageController.clear();

    setState(() {
      // 添加用户消息
      _messages.add({
        'isUser': true,
        'content': userMessage,
        'timestamp': DateTime.now(),
      });

      _isLoading = true;
    });

    // 滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToBottom();
    });

    // 构建历史消息
    final history = <Map<String, String>>[];

    // 添加初始的图片和问题
    history.add({
      'role': 'user',
      'content':
          'Please identify this marine life, reply in English，${widget.question}',
    });

    if (_scanResult != null) {
      history.add({'role': 'assistant', 'content': _scanResult!.result});
    }

    // 添加后续对话
    for (int i = 2; i < _messages.length - 1; i++) {
      // 跳过最初的图片和初始问题
      final message = _messages[i];
      if (message['content'] is String) {
        history.add({
          'role': message['isUser'] ? 'user' : 'assistant',
          'content': message['content'],
        });
      }
    }

    // 继续对话
    final response = await _aiService.continueConversation(
      question: userMessage,
      history: history,
    );

    setState(() {
      if (response != null) {
        // 添加AI回复
        _messages.add({
          'isUser': false,
          'content': response,
          'timestamp': DateTime.now(),
        });
      } else {
        // 添加错误消息
        _messages.add({
          'isUser': false,
          'content': 'Sorry, I cannot answer now. Please try again later.',
          'timestamp': DateTime.now(),
        });
      }
      _isLoading = false;
    });

    // 滚动到底部
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToBottom();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).pop();
                      },
                      child: Icon(
                        MyIcons.iconBack,
                        size: 24,
                        color: Colors.white,
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: Text(
                          'Ai species identification',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.sp,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            fontWeight: FontWeight.w400,
                            height: 1.36,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              // 聊天消息列表
              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: ListView.builder(
                    controller: _scrollController,
                    itemCount: _messages.length + (_isLoading ? 1 : 0),
                    itemBuilder: (context, index) {
                      // 加载指示器
                      if (_isLoading && index == _messages.length) {
                        return Align(
                          alignment: Alignment.centerLeft,
                          child: Container(
                            margin: EdgeInsets.symmetric(vertical: 10.h),
                            child: CircularProgressIndicator(
                              color: Colors.white,
                            ),
                          ),
                        );
                      }

                      // 聊天消息
                      final message = _messages[index];
                      final isUser = message['isUser'] as bool;
                      final content = message['content'];

                      if (content == 'image' && message['imageFile'] != null) {
                        // 图片消息
                        return Align(
                          alignment: Alignment.centerRight,
                          child: Container(
                            margin: EdgeInsets.only(bottom: 10.h, top: 5.h),
                            width: 150.w,
                            height: 150.w,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(15.r),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.5),
                                width: 1.w,
                              ),
                              image: DecorationImage(
                                image: FileImage(message['imageFile']),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                        );
                      } else {
                        // 文本消息
                        return Align(
                          alignment:
                              isUser
                                  ? Alignment.centerRight
                                  : Alignment.centerLeft,
                          child: Container(
                            constraints: BoxConstraints(maxWidth: 270.w),
                            margin: EdgeInsets.only(bottom: 10.h),
                            padding: EdgeInsets.all(12.w),
                            decoration:
                                isUser
                                    // 用户消息样式
                                    ? ShapeDecoration(
                                      color: const Color(0xFF121325),
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(30.r),
                                          topRight: Radius.circular(30.r),
                                          bottomLeft: Radius.circular(30.r),
                                          bottomRight: Radius.circular(4.r),
                                        ),
                                      ),
                                      shadows: [
                                        BoxShadow(
                                          color: const Color(0x99055FC6),
                                          blurRadius: 7,
                                          offset: const Offset(0, 1),
                                          spreadRadius: 0,
                                        ),
                                      ],
                                    )
                                    // AI消息样式
                                    : ShapeDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment(0.50, 0.00),
                                        end: Alignment(0.50, 0.86),
                                        colors: [
                                          const Color(0xFF0076FF).withAlpha(60),
                                          const Color(0xFF045EC6).withAlpha(60),
                                        ],
                                      ),
                                      shape: RoundedRectangleBorder(
                                        side: const BorderSide(
                                          width: 1,
                                          color: Color(0xFF0076FF),
                                        ),
                                        borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(30.r),
                                          topRight: Radius.circular(30.r),
                                          bottomLeft: Radius.circular(4.r),
                                          bottomRight: Radius.circular(30.r),
                                        ),
                                      ),
                                    ),
                            child: Text(
                              content as String,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                                fontFamily: GoogleFonts.inter().fontFamily,
                              ),
                            ),
                          ),
                        );
                      }
                    },
                  ),
                ),
              ),

              // 底部输入框
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
                margin: EdgeInsets.all(10.w),
                decoration: BoxDecoration(
                  color: Colors.black.withAlpha(100),
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(
                    color: Colors.blue.withAlpha(100),
                    width: 1.w,
                  ),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _messageController,
                        style: TextStyle(color: Colors.white, fontSize: 14.sp),
                        decoration: InputDecoration(
                          hintText: 'Say something',
                          hintStyle: TextStyle(
                            color: Colors.grey,
                            fontSize: 14.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 10.w,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: _isLoading ? null : _sendMessage,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment(0.50, 0.00),
                            end: Alignment(0.50, 0.86),
                            colors:
                                _isLoading
                                    ? [Colors.grey, Colors.grey.shade700]
                                    : [
                                      const Color(0xFF0076FF),
                                      const Color(0xFF045EC6),
                                    ],
                          ),
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                        child: Text(
                          'Send',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w400,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
